import os
import glob
import time
# import socket 
import subprocess  
import fcntl  
import struct  
from PIL import Image, ImageDraw, ImageFont  
import luma.oled as oled  
from luma.core.interface.serial import i2c    
from luma.oled.device import ssd1306  
  
WIDTH=128
HEIGHT=64   

LOCAL_PATH = "/home/pi/Desktop/oled/final-show-logo" #修改为脚本放置的目录
 
'''
def get_ip_address(ifname):    
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
    return socket.inet_ntoa(fcntl.ioctl(  
        s.fileno(),  
        0x8915,  # SIOCGIFADDR  
        struct.pack('256s', ifname[:15].encode('utf-8'))  # 将字符串编码为字节对象  
    )[20:24])
    return "10.11.96.77"
'''
  
def get_ip_address(interface='eth0'):  
    result = subprocess.run(['ip', '-f', 'inet', '-o', 'addr', 'show', interface], stdout=subprocess.PIPE, stderr=subprocess.PIPE)  
    output = result.stdout.decode()  
    if 'inet ' in output:  
        ip_info = output.split('inet ')[1].split('/')[0]  
        return ip_info  
    else:  
        return "loading......"  

def get_script_path():
    if '__file__' in globals():
        # 使用os.path.dirname来获取文件所在的文件夹
        script_dir = os.path.dirname(os.path.abspath(__file__))
        return script_dir
    else:
        return LOCAL_PATH
        
def search_dir_pic(dir_name, suffix):
    # 设置文件夹路径  
    # folder_path = os.path.join(os.getcwd(), dir_name)
    folder_path = os.path.join(SCRIPT_DIR, dir_name)
    print("图片路径")
    print(folder_path)
      
    # 使用glob模块匹配以数字命名的文件  
    number_files = glob.glob(os.path.join(folder_path, '[0-9]*.'+suffix)) 
    
    print('图片文件名')
    print(number_files)
    
    return sorted(number_files)
 
def load_device():
    # 创建I2C接口对象  
    serial = i2c(port=1, address=0x3C)  # 地址可能因显示屏型号而异  
      
    # 创建OLED设备对象  
    device = ssd1306(serial, WIDTH, HEIGHT) 
    
    return device
    
def draw_on_pic(image):
  
    # 创建一个可以在给定图像上绘制的对象  
    draw = ImageDraw.Draw(image)   
    # font = './font/ARIALI.TTF' 
    font = SCRIPT_DIR + '/font/ARIALI.TTF'
    font_size = int(min(WIDTH, HEIGHT)/5)
    font = ImageFont.truetype(font, font_size)
    # 使用函数获取eth0的IP地址  
    ip_address = get_ip_address('eth0')  
    port = 8000 #项目使用端口8000
    print("local eth0 addr "+ip_address)
    text = 'IP address:\n'+ip_address+'\nPort:\n'+str(port)
    # 定义文本内容和位置  
    x_position = 0  # x坐标  
    y_position = 0  # y坐标  
      
    # 在图片上写字，设置文本颜色为黑色  
    draw.text((x_position, y_position), text, fill=0, font=font)  
    
    # image.save('your_image_with_text.jpg')
    
    return image

# 定义一个函数来将灰度图像转换为二值图像  
def convert_to_binary(image, threshold=128):  
    return image.point(lambda x: 0 if x < threshold else 255, '1')   

def load_pic(pic_name):
    # 加载图片并调整大小  
    print('ready show pic '+pic_name)
    
    image = Image.open(pic_name)
    image = image.resize((WIDTH, HEIGHT)).convert('L')
    image = convert_to_binary(image) # 转换为二值图像（黑白） 
    image = draw_on_pic(image)

    return image
 
def show(image):
    # 将图片数据发送到OLED  
    device.display(image)
    time.sleep(1/5)
    
if __name__=='__main__':
    
    global SCRIPT_DIR
    SCRIPT_DIR = get_script_path()
    
    global device
    device = load_device()
    
    pic_group = search_dir_pic('logo', 'jpg')
    
    while True:
        for pic_file in pic_group:
            image = load_pic(pic_file)
            show(image)
        
        
    
